import redisHandle from './redisHandle'
import app from 'src/app'
import mongodbHandle from './mongodbHandle'
var ObjectId = require('mongodb').ObjectId;
import * as moment from 'moment'
import utils from 'src/core/utils';
// import { battleHandle } from 'js/handle/battleHandle';
import Random from 'js/core/random';
// import arenaHandle from 'js/handle/arenaHandle';
import * as schedule from 'node-schedule'
import { PlayerModel } from 'js/model/playerModel';
import arenaHandle from './arenaHandle';
class ArenaAutoHandle {
    addPlayer(pID) {
        redisHandle.sadd(app.config.gameName + 'arenaAuto', pID)
    }
    init = async () => {
        schedule.scheduleJob('0 1 * * * *', async () => {
            console.log('自动匹配开始')
            await this.auto()
            console.log('自动匹配结束')
        });

        schedule.scheduleJob('0 20 23 * * *', async () => {
            mongodbHandle.arenaDao.remove({ time: { $lte: moment().add(-3, 'day').valueOf() } })
        })
    }

    auto = async () => {
        let smembers = await redisHandle.smembers(app.config.gameName + 'arenaAuto')
        if (smembers) {
            console.log('自动匹配:', smembers.length)
            for (let i = 0; i < smembers.length; i++) {
                let pID = smembers[i]
                let myData = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
                if (!myData) {
                    continue
                }
                if (i % 200 == 0) {
                    console.log(i)
                    await utils.setTimeout(50)
                }

                let nowTime = new Date().getTime()
                if (nowTime > (myData.loginTime + 2 * 24 * 60 * 60 * 1000)) {
                    await redisHandle.srem(app.config.gameName + 'arenaAuto', pID)
                    continue;
                }

                myData.arenaTimes = (myData.arenaTimes || 0)
                let arenaTime = myData.arenaTime, dayTime = moment().startOf('day').valueOf()
                if (arenaTime !== dayTime) {
                    myData.arenaTimes = 0
                    myData.arenaTime = dayTime
                }
                if (myData.arenaTimes >= 15) {
                    continue;
                }
                // let data = await this.getOpponent(pID, myData)
                // if (data.opponent) {
                //     data.my.playerData = playerHandle.initPlayer(data.my.playerData, 0, false)
                //     data.opponent.playerData = playerHandle.initPlayer(data.opponent.playerData, 0, false)
                //     let p1 = playerHandle.getFightAttriTeam(data.my.playerData, false, true)
                //     let p2 = playerHandle.getFightAttriTeam(data.opponent.playerData, false, true)
                //     let p1str = JSON.stringify(p1)
                //     let p2str = JSON.stringify(p2)
                //     let random = new Random()
                //     let seed = random.getSeed()
                //     // let { result } = await battleHandle.start(p1, p2, seed, 2)
                //     // let arenaSettlementData = this.arenaSettlement(result, data.my.arenaScore, data.opponent.arenaScore)
                //     // myData.arenaTimes += 1
                //     // this.saveArenaData(pID, data.opponent._id.toString(), p1str, p2str, arenaSettlementData.addScore1, arenaSettlementData.addScore2, result, app.version, seed, arenaSettlementData.point, myData, data.opponent)
                // }
            }
        }
    }

    // arenaSettlement = (result, score1, score2) => {
    //     let info = arenaHandle.getBattleScore(score1, score2, result)
    //     return info
    // }
    // saveArenaData = async (p1ID, p2ID, player1, player2, addScore1, addScore2, result, version, seed, point, myData, otherData) => {
    //     if (Math.abs(addScore1) > 25) {
    //         return { err: 1 }
    //     }
    //     if (Math.abs(addScore2) > 10) {
    //         return { err: 2 }
    //     }
    //     let max = arenaHandle.getArenaScoreMax()
    //     if (myData) {
    //         let myOriginScore = arenaHandle.getArenaScore(myData.arenaScore)
    //         let myScore = myOriginScore + Math.floor(addScore1)
    //         if (myScore <= 1) {
    //             myScore = 1
    //         }
    //         if (myScore > max) {
    //             myScore = max
    //         }
    //         myData.arenaScore = arenaHandle.setArenaScore(myData.arenaScore, myScore, moment().valueOf())
    //         await mongodbHandle.playerDao.updateOne({
    //             _id: ObjectId(p1ID),
    //         }, {
    //             $set: {
    //                 arenaScore: myData.arenaScore,
    //                 arenaTimes: myData.arenaTimes,
    //                 arenaTime: myData.arenaTime,
    //                 arenaPoint: (myData.arenaPoint || 0) + (point || 0)
    //             }
    //         })
    //     }

    //     if (otherData) {
    //         let otherOriginScore = arenaHandle.getArenaScore(otherData.arenaScore)
    //         let otherScore = otherOriginScore + Math.floor(addScore2)
    //         if (otherScore <= 1) {
    //             otherScore = 1
    //         }
    //         if (otherScore > max) {
    //             otherScore = max
    //         }
    //         otherData.arenaScore = arenaHandle.setArenaScore(otherData.arenaScore, otherScore, moment().valueOf())
    //         await mongodbHandle.playerDao.updateOne({
    //             _id: ObjectId(p2ID),
    //         }, {
    //             $set: {
    //                 arenaScore: otherData.arenaScore
    //             }
    //         })
    //         await mongodbHandle.arenaDao.newAndSave(myData.name, otherData.name, p1ID, p2ID, player1, player2, Math.floor(addScore1), Math.floor(addScore2), point, result, seed, version, 1)
    //     }
    //     return { err: 0 }
    // }

    saveArenaData2 = async (p1ID, p2ID, player1, player2, addPoint1, addPoint2, result, version, seed, point, myData, otherData) => {
        if (Math.abs(addPoint1) > 25) {
            return { err: 1 }
        }
        if (Math.abs(addPoint2) > 10) {
            return { err: 2 }
        }
        let max = arenaHandle.getArenaPointMax()
        if (myData) {
            let myOriginPoint = myData.arenaPoint
            let myPoint = myOriginPoint + Math.floor(addPoint1)
            if (myPoint <= 1) {
                myPoint = 1
            }
            if (myPoint > max) {
                myPoint = max
            }
            myData.arenaPoint = myPoint
            myData.arenaTime += 1
            let res = await mongodbHandle.playerDao.updateOne({
                _id: ObjectId(p1ID),
            }, {
                $set: {
                    arenaPoint: myData.arenaPoint,
                    arenaTimes: myData.arenaTimes,
                    arenaTime: myData.arenaTime,
                }
            })
        }

        if (otherData) {
            if (p1ID != p2ID) {
                let otherOriginPoint = otherData.arenaPoint
                let otherPoint = otherOriginPoint + Math.floor(addPoint2)
                if (otherPoint <= 1) {
                    otherPoint = 1
                }
                if (otherPoint > max) {
                    otherPoint = max
                }
                otherData.arenaPoint = otherPoint
                await mongodbHandle.playerDao.updateOne({
                    _id: ObjectId(p2ID),
                }, {
                    $set: {
                        arenaScore: otherData.arenaPoint
                    }
                })
            } else {
                p2ID = p2ID.split("").reverse().join("")
            }
            let name1 = myData.playerData.playerName || '玩家' + myData._id.toString().substr(-4)
            let name2 = otherData.playerData.playerName || '玩家' + otherData._id.toString().substr(0, 4)
            await mongodbHandle.arenaDao.newAndSave(name1, name2, p1ID, p2ID, player1, player2, Math.floor(addPoint1), Math.floor(addPoint2), point, result, seed, version, 1)
        }
        return { err: 0 }
    }

    // getOpponent = async (pID, myData) => {
    //     let myScore = myData.arenaScore || 0
    //     let addScore = 0
    //     if (myScore < 200 * arenaHandle.arenaScoreBaseTime) {
    //         addScore = 0
    //     } else if (myScore < 300 * arenaHandle.arenaScoreBaseTime) {
    //         addScore = Math.floor(myScore * 0.1)
    //     } else if (myScore < 400 * arenaHandle.arenaScoreBaseTime) {
    //         addScore = Math.floor(myScore * 0.12)
    //     } else if (myScore < 600 * arenaHandle.arenaScoreBaseTime) {
    //         addScore = Math.floor(myScore * 0.15)
    //     } else if (myScore < 800 * arenaHandle.arenaScoreBaseTime) {
    //         addScore = Math.floor(myScore * 0.2)
    //     } else {
    //         addScore = Math.floor(myScore * 0.25)
    //     }
    //     if (addScore < 10 * arenaHandle.arenaScoreBaseTime) {
    //         addScore = 10 * arenaHandle.arenaScoreBaseTime
    //     }
    //     let time = moment().add(-3, 'days').valueOf()
    //     let docs = await mongodbHandle.playerDao.findByPageAndSort({
    //         currentServerID: myData.currentServerID,
    //         "cheat": {
    //             $ne: true
    //         },
    //         "loginTime": {
    //             $gt: time
    //         },
    //         "arena": true,
    //         "arenaScore": {
    //             $lte: myScore + addScore
    //         },
    //     }, {
    //         "arenaScore": -1
    //     }, 0, 40)
    //     let players: any[] = []
    //     if (docs && docs.length > 0) {
    //         for (let i = 0; i < docs.length; i++) {
    //             let doc = docs[i]
    //             if (doc._id.toString() !== pID) {
    //                 players.push(doc)
    //             }
    //         }
    //     }
    //     if (players.length > 0) {
    //         let i = Math.floor(Math.random() * players.length)
    //         return { opponent: players[i], my: myData, delete: false }
    //     } else {
    //         let docs = await mongodbHandle.playerDao.findByPageAndSort({
    //             currentServerID: myData.currentServerID,
    //             "cheat": {
    //                 $ne: true
    //             },
    //             "loginTime": {
    //                 $gt: time
    //             },
    //             "arena": true,
    //             "arenaScore": {
    //                 $gte: myScore
    //             },
    //         }, {
    //             "arenaScore": 1
    //         }, 0, 40)

    //         if (docs && docs.length > 1) {
    //             for (let i = 0; i < docs.length; i++) {
    //                 let doc = docs[i]
    //                 if (doc._id.toString() !== pID) {
    //                     players.push(doc)
    //                 }
    //             }
    //         }
    //         if (players.length > 0) {
    //             let i = Math.floor(Math.random() * players.length)
    //             return { opponent: players[i], my: myData, delete: false }
    //         } else {
    //             return { opponent: myData, my: myData, delete: false }
    //         }
    //     }
    // }
}


let arenaAutoHandle = new ArenaAutoHandle()
export default arenaAutoHandle